<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 售后
 * Class Service
 * @author heyu
 */
class Service extends MY_Controller {

    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
		
        $data = array(
            'serviceType' => $this->mOrder->serviceType(),
            'title' => '售后管理'
        );
		$this->view('order/service/home', $data, 'datatable,datepicker');
	}

    /**
     * 获取列表
     */
    public function getList(){
        $data = $this->mOrder->adminPcGetOrderServiceList();
        if ($data['data']){
            foreach ($data['data'] as $k => $v){
                $data['aaData'][$k][] = $v['code'];
                $data['aaData'][$k][] = $v['order_code'];
                $data['aaData'][$k][] = $v['shop_name'];
                $data['aaData'][$k][] = $v['name'];
                $data['aaData'][$k][] = $v['remark'];
                $data['aaData'][$k][] = $v['refund_amount'];
                $data['aaData'][$k][] = dateFormat($v['addtime']);
                $data['aaData'][$k][] = $this->mOrder->serviceType($v['status'], true);
                $btnConfig = adminCreateBtn(array(
                    'label' => '查看',
                    'attr' => array(
                        'href' => getUrl('order/service/details?code='.$v['code']),
                        'class' => 'btn green-stripe btn-xs default'
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'order',
                        'key' => 'service-details'
                    )
                ));
                $data['aaData'][$k][] = $btnConfig;
            }
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 详情
     */
    public function details(){
        $code = get('code');
        $serviceInfo = $this->mOrder->getServiceInfo($code);  // 售后信息
        if (empty($serviceInfo)){
            show_404();
        }
        $info = $this->mOrder->getInfo($serviceInfo['order_id']);  // 订单信息
        $oP = $this->mOrder->getOrderProductInfoByIds(array(), $serviceInfo['order_id']); // 订单商品信息

        $data = array(
            'info' => $info,
            'serviceInfo' => $serviceInfo,
            'oP' => empty($oP) ? array() : $oP[$serviceInfo['order_id']],
            'backUrl' => getUrl('order/service'),
            'title' => '售后详情'
        );
        $this->view('order/service/details', $data, 'datatable,validation,region,select2');
    }

    /**
     * 保存数据
     */
    public function saveService(){
        //表单验证
        $vConf = array(
            array('code', 'code', 'required'),
            array('status', 'status', 'required|in_list[2,4]'),
            array('complete_remark', '操作备注', 'required'),
            array('refund_amount', '退款金额', 'required'),
        );
        $this->formDataValidation($vConf, array('code' => get('code')));
        $code = post('code');
        $refAmount = post('refund_amount'); // 新修改退款金额
        $status = (int)post('status');
        $info = $this->mOrder->getServiceInfo($code);  // 售后信息
        if (empty($info)){
            $this->ajaxReturn(0, '售后信息不存在');
        }
        if ($info['status'] != 3 && $info['status'] != 4){
            $this->ajaxReturn(0, '不能操作售后处理');
        }
        $this->db->trans_begin();
        // 确认退款
        if ($status == 2){
            $result = $this->mOrder->_agreeRefund($info, $refAmount);
            if($result['status'] == 0){

                $this->db->trans_rollback();
                $this->ajaxReturn(0, $result['message']);
            }

        }else{
            $result = $this->mOrder->_orderServiceMessage($info, 2);
            if($result['status'] == 0){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, $result['message']);
            }
        }

        // 修改售后情况
        $data = array(
            'platform_remark' => post('platform_remark'), // 平台备注
            'status' => $status,
            'complete_time' => time()
        );
        $tA = $this->mOrder->saveService($data, $code);
        if (!$tA){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }

        //订单商品全部售后完成 改变订单状态为交易关闭
        if(!($this->mOrder->save(array('status' => 6), 0, $info['order_id']))){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        // 添加操作记录
        $note = trim(post('note'));
        $rS = $this->mOrder->saveOrderLog($info['order_id'], '售后完成', $note,$this->port, $this->userId);
        if (!$rS){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $bData['status_format_str'] = $this->mOrder->serviceType($data['status'], true);
        $bData['complete_time'] = dateFormat($data['complete_time'], true);
        $bData['status'] = $data['status'];
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', $bData);
    }

    /**
     * 导出
     */
    public function export(){
        $filename = '售后管理'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('售后单号,订单号,商家,退款商品,退款原因,退款金额,申请时间,状态','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        while(true){
            $data = $this->mOrder->adminPcGetOrderServiceList(0, 0, array(), array('page' => $page, 'pageNumber' => $pageNumber));
            if(empty($data)){
                break;
            }
            $page ++;
            foreach($data as $v){
                $addtime = dateFormat($v['addtime']);
                $status = $this->mOrder->serviceType($v['status']);
                echo mb_convert_encoding($v['code']."\t".','.$v['order_code']."\t".','.$v['shop_name'].','.$v['name'].','.$v['remark'].','.$v['refund_amount'].','.$addtime.','.$status, 'gb2312','utf-8')."\n";
            }
        }
    }
}
